<?php

/**
 * @author shadow245
 * @copyright 2013
 */

class Model {
    protected $_db;
    protected $_table;
    protected $_ruta;
    protected $_query;
    protected $_ext;
    public $_data;
    
    public function __construct($table = '',$extension = '',$ruta = ''){
        $this->_table = $table;
        $this->_ext = $extension;
        $this->_ruta = $ruta;
    }
    
    function open($readOnly = true){
        $mode = $readOnly ? "Read" : "3";
        $cf = new Config();
        $this->_db = new DatabaseDux($cf->config['DB']['DUX'],$this->_ruta,true,$mode);
        error_log($this->getTable(true) . " :: Tabla abierta el " . date('Y-m-d G:i:s'));
    }
    
    function close(){
        $this->_db->disconnect();
        error_log($this->getTable(true) . " :: Tabla cerrada el " . date('Y-m-d G:i:s'));
    }
    
    public function getLast($campo,$val = ''){
        $where = $val != '' ? "WHERE $campo = $val" : "";
        $data = $this->lista('
            SELECT *
            FROM ' . $this->getTable(true) . "
            $where
            ORDER BY $campo DESC"
        );
        return $data[0][strtolower($campo)];
    }
    
    public function lista($sql){
        $this->_db->setQuery($sql);
        return $this->_db->fetchArrayListEx();
    }
    
    public function row($sql){
        $this->_db->setQuery($sql);
        $datos = $this->_db->fetchArrayListEx();
        return $datos[0];
    }
    
    public function insert($datos){
        if(!isset($this->_table)){
            return false;
        }
        
        if(!is_array($datos)){
            return false;
        }
        
        foreach($datos as $data){
            foreach(array_keys($data) as $key){
                if(!is_numeric($data[$key])){
                    $data[$key]= "'" . $data[$key] . "'";
                }
                
                if(preg_match('/\d{4}-\d{2}-\d{2}/', $data[$key])){
                    $data[$key] = "{d " . $data[$key] . "}";
                }
            }
            $rows = implode(",", array_keys($data));
            $values = "(" . implode(", ",$data) . ")";
            $values = str_replace("''","'",$values);
            $this->_db->setQuery('INSERT INTO ' . $this->getTable(true) . " ($rows) VALUES $values");
        }
        /*$values = implode(",", $values);
        $values = str_replace("''","'",$values);
        
        echo 'INSERT INTO ' . $this->getTable(true) . " ($rows) VALUES $values <br/>";
        $this->_db->setQuery('INSERT INTO ' . $this->getTable(true) . " ($rows) VALUES $values");*/
        return true;
    }
    
    public function edit($campo,$id, $datos){
        if(!isset($this->_table)){
            return false;
        }
        
        $sets = "";

        unset($datos[$campo]);
        
        foreach(array_keys($datos) as $key){
            if(is_numeric($datos[$key])){
                $sets .= $key . " = " . $datos[$key] . ", ";
            }else{
                $sets .= $key . " = '" . $datos[$key] . "', ";
            }
        }
        
        $sets = substr($sets,0, strlen($sets)-2);
        $this->_db->executeQuery('UPDATE ' . $this->getTable(true) . " SET $sets WHERE $campo = $id");
    }
        
    public function gets($where = '',$orderBy = ''){
        $orderBy = $orderBy != '' ? "ORDER BY $orderBy" : "";
        
        //echo 'SELECT * FROM ' . $this->getTable(true,$this->_table) . " $orderBy";exit;
        $this->_db->setQuery('SELECT * FROM ' . $this->getTable(true,$this->_table) . " $orderBy");
        return $this->_db->fetchArrayListEx();
    }
    
    public function get($campo,$id){
        //echo 'SELECT * FROM ' . $this->getTable(true,$this->_table) . " WHERE $campo = $id";
        $this->_db->setQuery('SELECT * FROM ' . $this->getTable(true,$this->_table) . " WHERE $campo = $id");
        $datos = $this->_db->fetchArrayListEx();
        
        if($this->_db->rowCount == 0 ){
            if(count($this->_data) != 0 ){
                foreach($this->_data as $key => $val ){
                    unset($this->{"_".$key});
                }
                $this->_data = null;
            }
            return false;
        }
        
        $this->_data = $datos[0];
        $data = &$this->_data;
        
        while(key($data)){
            $this->{"_" . key($data)} = &$data[key($data)];
            next($data);
        }
        return true;
    }
    
    public function get2($sql){
        //echo 'SELECT * FROM ' . $this->getTable(true,$this->_table) . " WHERE $campo = $id";
        $this->_db->setQuery($sql);
        $datos = $this->_db->fetchArrayListEx();
        
        if($this->_db->rowCount == 0 ){
            return false;
        }
        
        $this->_data = $datos[0];
        $data = &$this->_data;
        
        while(key($data)){
            $this->{"_" . key($data)} = &$data[key($data)];
            next($data);
        }
        return true;
    }
    
    public function getTable($dux = false, $alias =''){
        if($dux)
            return '"' . $this->_table . '.' . $this->_ext . '" ' . $alias;
        return $this->_table; 
    }
    
    function checkDate($str){ /// dead useful when validating between mysql and php date formats
        trim($str);
        $temp = explode("-",$str);
        
        if(count($temp) < 3){
            return false;
        }
        
        $dia = 1*$temp[2];
        $mes = $temp[1];
        $anio = 1*$temp[0];
        
        if(!checkdate($mes,$dia,$anio)){
            //echo $mes;exit;
            return false;
        }
           
        return true;
    }
}

class Model2 {
    protected $_db;
    protected $_table;
    protected $_query;
    protected $_cf;
    protected $database = 'MYSQL';
    public $_data;
    
    
    public function __construct($table = ''){
        $this->_table = $table;
    }
    
    public function open($readOnly = false,$database='MYSQL'){
        $this->_cf = new Config();
        $this->_db = new Database($this->_cf->config['DB'][$this->database]);
        
        if(!is_null($this->_table))
            $this->_query = $this->_db->_query("SELECT * FROM " . $this->_table);
    }
    
    public function close(){
        return ;
    }
    
    public function lastId(){
        return $this->_db->lastInsertId();
    }
    
    public function lista($sql){
        //echo $sql . "<br />";
        $this->setQuery($sql);
        return $this->_list();
    }
    
    public function _list(){ //OBTIENE TODOS LOS DATOS
        return $this->_query->fetchAll(PDO::FETCH_ASSOC);
    }
    
    public function _colums(){ //OBTIENE LOS NOMBRES DE LOS CAMPOS
        $total_column = $this->_query->columnCount();

        for ($counter = 0; $counter < $total_column; $counter ++) {
            $meta = $this->_query->getColumnMeta($counter);
            $column[] = $meta['name'];
        }
        return $column;
    }
    
    public function setQuery($query){
        //echo $query;
        $this->_query = $this->_db->_query($query);
    }
    
    public function getTable(){
        return strtoupper($this->_table);
    }
    
    public function delete($campo,$id){
        $this->setQuery('DELETE FROM ' . $this->_table . " WHERE $campo = $id");
    }
    
    public function insert($data){
        if(!isset($this->_table)){
            return false;
        }
        
        if(!is_array($data)){
            return false;
        }
        
        foreach(array_keys($data) as $key){
            if(!is_numeric($data[$key])){
                $data[$key]= $data[$key] == '' ? "''''" : "'" . $data[$key] . "'";
            }
            
        }
        
        $rows = implode(", ", array_keys($data));
        $values = implode(", ",$data);
        $values = str_replace("''","'",$values);
        $values = str_replace("'on'","1",$values);
        $this->open(false,$this->database);
        $this->setQuery('INSERT INTO ' . $this->_table . " ($rows) VALUES ($values)");
        $this->close();
        return true;
    }
    
    public function update($data,$where){
        if(!isset($this->_table)){
            return false;
        }

        if(!is_array($data)){
            return false;
        }
        
        array_filter($data);
        
        foreach(array_keys($data) as $key){
            if(!is_numeric($data[$key])){
                $data[$key]= $data[$key] == '' ? "''''" : "'" . $data[$key] . "'";
            }
            
            if(preg_match('/\d{4}-\d{2}-\d{2}/', $data[$key])){
                $data[$key] = "'" . $data[$key] . "'";
            }
            
            $values[] = "$key = " . $data[$key];
        }
        
        $values = implode(", ",$values);
        $values = str_replace("''","'",$values);
        $values = str_replace("'on'","1",$values);
        $this->open(false,$this->database);
        //echo 'UPDATE ' . $this->_table . " SET $values WHERE $where";exit;
        $this->setQuery('UPDATE ' . $this->_table . " SET $values WHERE $where");
        $this->close();
        return true;
    }
    
    public function get($campo,$id){
        $this->open(false,$this->database);
        //echo 'SELECT * FROM ' . $this->_table . " WHERE $campo = $id";
        $this->setQuery('SELECT * FROM ' . $this->_table . " WHERE $campo = $id");
        $this->close();
        $datos = $this->_list();
        
        if(count($datos) == 0 ){
            if(count($this->_data) != 0 ){
                foreach($this->_data as $key => $val ){
                    unset($this->{"_".$key});
                }
                $this->_data = null;
            }
            return false;
        }
        
        $this->_data = $datos[0];
        $data = &$this->_data;
        
        while(key($this->_data)){
            $this->{"_" . key($this->_data)} = &$this->_data[key($this->_data)];
            next($this->_data);
        }
        return true;
    }
    
    public function _gets(){
        $this->setQuery('SELECT * FROM ' . $this->_table);
        $datos = $this->_list();
        
        if(count($datos) == 0 ){
            return false;
        }
        
        $this->_data = $datos;
        return true;
    }
}
class Model3 {
    protected $_db;
    protected $_table;
    protected $_query;
    public $_data;
    
    public function __construct($table = ''){
        $this->_table = $table;
    }
    
    public function open($readOnly = false){
        $cf = new Config();
        $this->_db = new DatabaseSQLServer($cf->config['DB']['MSSQL']);
        $this->_db->connect();
    }
    
    public function close(){
        $this->_db->close();
    }
    
    public function lista($sql){
        $this->_db->executeQuery($sql);
        return $this->_db->fetchArrayListEx();
    }
    
    public function row($sql){
        $this->_db->executeQuery($sql);
        $datos = $this->_db->fetchArrayListEx();
        return $datos[0];
    }
    
    public function insert($data){
        if(!isset($this->_table)){
            return false;
        }
        
        if(!is_array($data)){
            return false;
        }
        
        foreach(array_keys($data) as $key){
            if(!is_numeric($data[$key])){
                $data[$key]= "'" . $data[$key] . "'";
            }
        }
        
        $rows = implode(", ", array_keys($data));
        $values = implode(", ",$data);
        //echo "INSERT INTO " . $this->_table . " ($rows) VALUES ($values)";exit;
        $this->_db->executeQuery("INSERT INTO " . $this->_table . " ($rows) VALUES ($values)");
        return true;
    }
    
    public function edit($campo,$id, $datos){
        if(!isset($this->_table)){
            return false;
        }
        
        $sets = "";

        unset($datos[$campo]);
        
        foreach(array_keys($datos) as $key){
            if(is_numeric($datos[$key])){
                $sets .= $key . " = " . $datos[$key] . ", ";
            }else{
                $sets .= $key . " = '" . $datos[$key] . "', ";
            }
        }
        
        $sets = substr($sets,0, strlen($sets)-2);
        $this->_db->executeQuery("UPDATE " . $this->_table . " SET $sets WHERE $campo = $id");
    }
        
    public function del($campo,$id){
        if(!isset($this->_table)){
            return false;
        }
        
        $this->_db->executeQuery("DELETE FROM " . $this->_table . " WHERE $campo = $id");
        return true;
    }
    
    public function gets(){
        $this->_db->executeQuery("SELECT * FROM " . $this->_table);
        return $this->_db->fetchArrayListEx();
    }
    
    public function get($campo,$id){
        $id = (int) $id;
        $this->_db->executeQuery("SELECT * FROM " . $this->_table . " WHERE $campo = $id");
        $datos = $this->_db->fetchArrayListEx();
        
        if($this->_db->rowCount == 0 ){
            if(count($this->_data) != 0 ){
                foreach($this->_data as $key => $val ){
                    unset($this->{"_".$key});
                }
                $this->_data = null;
            }
            return false;
        }
        
        $this->_data = $datos[0];
        $data = &$this->_data; 
        
        while(current($data) != null){
            $this->{"_" . key($data)} = &$data[key($data)];
            next($data);
        }
        return true;
    }
}

class Model4 {
    protected $dbma;
    protected $db;
    protected $param;
    public $data;
    
    public function __construct(){
        $cf = new Config();
        $DB = $dbma . "_DB";
        $this->db = new $DB;
    }
    
    function open(){}
    
    function close(){}
    
    public function insertar($datos){}
    public function editar($data,$where){}
    public function eliminar($campo,$id){}
    public function lista($sql){}
    public function registro($sql){}



    public function gets($where = '',$orderBy = ''){}
    public function get($campo,$id){}
    public function get2($sql){}
    public function getTable($dux = false, $alias =''){}
    public function checkDate($str){}
    public function lastId(){}
    public function _colums(){}
    public function setQuery($query){}
    public function _gets(){}
    public function del($campo,$id){}
}
?>